package com.demo.gulimall.seckill.schedule;

import com.demo.gulimall.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 秒杀商品定时上架
 * @author Chen Yuan
 * @create 2023-08-07  15:00
 */
@Slf4j
@Component
public class SeckillSkuSchedule {
	private final static String UPLOAD_LOCK_KEY = "seckill:uploadLock";

	@Autowired
	private SeckillService seckillService;

	@Autowired
	private RedissonClient redissonClient;

	/**
	 * 每天晚上 3 点上架最近3天需要上架的商品
	 */
	@Scheduled(cron = "0 0 3 * * *")
	public void uploadSeckillSkuLatestThreeDays(){
		// 分布式锁, 只有一个服务能进行操作
		RLock lock = redissonClient.getLock(UPLOAD_LOCK_KEY);
		lock.lock(10, TimeUnit.SECONDS);

		try {
			seckillService.uploadSeckillSkuLatestThreeDays();
		} finally {
			lock.unlock();
		}
	}
}
